package org.jash.learnmvp.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.datepicker.SingleDateSelector;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.dialog.MaterialDialogs;
import com.google.android.material.navigation.NavigationView;
import com.hyphenate.chat.EMClient;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.jash.learnmvp.R;
import org.jash.learnmvp.map.MapActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class MineFragment extends Fragment {
    private NavigationView navigation;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private DrawerLayout drawer;
    private MaterialToolbar toolbar;
    private ImageView icon;
    private ActivityResultLauncher<Void> launcher;
    private ActivityResultLauncher<String> getImage;


    public MineFragment() {
        super(R.layout.fragment_mine);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launcher = registerForActivityResult(new ActivityResultContracts.TakePicturePreview(), bitmap -> icon.setImageBitmap(bitmap));
        getImage = registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> icon.setImageURI(uri));
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        view.findViewById(R.id.logout).setOnClickListener(v -> {
            Disposable disposable = Observable.fromAction(() -> EMClient.getInstance().logout(true))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(r -> {
                    }, t -> {
                        Toast.makeText(requireContext(), "退出失败:" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }, () -> {
                        Toast.makeText(requireContext(), "退出成功", Toast.LENGTH_SHORT).show();
//                        startActivity(new Intent(requireContext(), MainActivity.class));
//                        requireActivity().finish();
                    });
        });
        navigation = view.findViewById(R.id.navigation);
        drawer = view.findViewById(R.id.drawer);
        toolbar = view.findViewById(R.id.toolbar);
        icon = view.findViewById(R.id.icon);
        icon.setOnClickListener(v -> {
//            launcher.launch(null);
            getImage.launch("image/*");
        });
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(requireActivity(), drawer, toolbar, 0, 0);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigation.setNavigationItemSelectedListener(item -> {
            if (item.getItemId() == R.id.mine_qrcode) {
                String currentUser = EMClient.getInstance().getCurrentUser();
                Bitmap image = CodeUtils.createImage(currentUser, 300, 300, null);
                ImageView imageView = new ImageView(requireContext());
                imageView.setImageBitmap(image);
                new MaterialAlertDialogBuilder(requireContext())
                        .setView(imageView)
                        .create().show();
            } else if (item.getItemId() == R.id.gender) {
                View v = getLayoutInflater().inflate(R.layout.dialog_gender, null);
                RadioGroup gender = v.findViewById(R.id.gender);
                new MaterialAlertDialogBuilder(requireContext())
                        .setView(v)
                        .setTitle("选择性别")
                        .setPositiveButton("确定", (d, i) -> {
                            if (gender.getCheckedRadioButtonId() == R.id.male) {
                                item.setTitle("性别:男");
                            } else {
                                item.setTitle("性别:女");
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create().show();
            } else if(item.getItemId() == R.id.birthday) {
                try {
                    String s = item.getTitle().toString().split(":")[1].trim();
                    MaterialDatePicker<Long> picker = MaterialDatePicker.Builder.datePicker()
                            .setTitleText("选择生日")
                            .setNegativeButtonText("确定")
                            .setNegativeButtonText("取消")
                            .setSelection(sdf.parse(s).getTime())
                            .build();
                    picker.addOnPositiveButtonClickListener(l -> {
                        item.setTitle("生日:" + sdf.format(new Date(l)));
                    });
                    picker.show(getChildFragmentManager(), null);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

            } else if (item.getItemId() == R.id.m6) {
                requireContext().startActivity(new Intent(requireContext(), MapActivity.class));
            }
            return true;
        });

    }
}